/*异步日志缓冲区*/
#ifndef __M_BUF_M__
#define __M_BUF_M__

#include "util.hpp"
#include <vector>

namespace log
{
#define DEFAUTL_BUFFER_SIZE (10 * 1024 * 1024)
#define THRESHOLD_BUFFER_SIZE (80 * 1024 * 1024)
#define INCREAMENT_BUFFER_SIZE (10 * 1024 * 1024)
    class Buffer
    {
    public:
        Buffer() : _buffer(DEFAUTL_BUFFER_SIZE), _reader_idx(0), _writer_idx(0)
        {
        }
        void push(const char *data, size_t len) // 写入数据
        {
            // 扩容
            getSpace(len);
            std::copy(data, data + len, &_buffer[_writer_idx]);
            moveWriter(len);
        }
        const char *begin() // 返回可读数据的起始位置
        {
            return &_buffer[_reader_idx];
        }
        size_t writeAbleSize() // 可写数据长度
        {
            // 扩容就不需要，只针对固定缓冲区而设计
            return _buffer.size() - _writer_idx;
        }
        size_t readAbleSize() // 可读数据长度
        {
            return _writer_idx - _reader_idx;
        }
        void moveReader(size_t len) // 移动读指针
        {
            assert(len <= readAbleSize());
            _reader_idx += len;
        }
        void reset() // 重置读写位置，初始化缓冲区
        {
            _reader_idx = _writer_idx = 0;
        }
        void swap(Buffer &buffer) //  交换缓冲区
        {
            _buffer.swap(buffer._buffer);
            std::swap(buffer._writer_idx, _writer_idx);
            std::swap(buffer._reader_idx, _reader_idx);
        }
        bool empty() //  判空
        {
            return _writer_idx == _reader_idx;
        }

    private:
        void getSpace(size_t len)
        {
            if (len <= writeAbleSize())
                return;
            size_t new_size = 0;
            if (THRESHOLD_BUFFER_SIZE >= _buffer.size())
            {
                new_size = _buffer.size() * 2 + len;
            }
            else
            {
                new_size = _buffer.size() + INCREAMENT_BUFFER_SIZE + len;
            }
            _buffer.resize(new_size);
        }
        void moveWriter(size_t len) // 移动写指针
        {
            assert(len <= writeAbleSize());
            _writer_idx += len;
        }

    private:
        std::vector<char> _buffer; // 缓冲区
        size_t _reader_idx;        // 读数据指针
        size_t _writer_idx;        // 写数据指针
    };
}
#endif